<template>
	<div class="wrapper">
		<header>
			<p class="back-btn" @click="$router.go(-1)">〈</p>
			<p>虚拟钱包</p>
		</header>

		<div class="content-box">
			<div class="wallet-summary">
				<div class="summary-item">
					<span>当前余额</span>
					<strong>{{ balance.toFixed(2) }}</strong>
				</div>
			</div>

			<!-- 如果没有钱包，显示创建钱包按钮 -->
			<div v-if="!user.walletId" class="create-wallet-btn">
				<button @click="createWallet">创建钱包</button>
			</div>

			<!-- 如果有钱包，显示充值和提现操作 -->
			<div v-if="user.walletId" class="wallet-actions">
				<h3>操作</h3>
				<div class="action-item">
					<input v-model.number="rechargeAmount" type="number" placeholder="充值金额" />
					<button @click="recharge">充值</button>
				</div>

				<div class="action-item">
					<input v-model.number="withdrawAmount" type="number" placeholder="提现金额" />
					<button @click="withdraw">提现</button>
				</div>
			</div>
		</div>

		<Footer></Footer>
	</div>
</template>
<script>
import Footer from '../components/Footer.vue';

export default {
	name: 'VirtualWallet',
	data() {
		return {
			balance: 0,
			rechargeAmount: 0,
			withdrawAmount: 0,
			user: {}, // 确保 user 初始为对象，避免 undefined 访问 userId
			walletId:'',
		};
	},
	created() {
		this.user = this.$getSessionStorage('user') || {}; // 确保 this.user 不为空
		this.checkOrCreateWallet();
	},
	methods: {
		// 检查是否有钱包，没有则创建
		checkOrCreateWallet() {
			if (!this.user.userId) {
				console.error('用户信息缺失，无法查询钱包');
				alert('用户未登录或信息异常');
				return;
			}

			this.$axios.get('VirtualWallet/UserId',{
					params: {
						userId: this.user.userId
					}})
				.then(res => {
					if (!res.data.result) {
						// 如果没有钱包，显示创建钱包按钮
						this.user.walletId = null;
					} else {
						this.user.walletId = res.data.result;
						this.loadBalance();
					}
				}).catch(err => {
					console.error('获取钱包失败:', err.response || err);
					alert('获取钱包失败: ' + (err.response?.data?.message || err.message));
				});
		},

		// 创建钱包
		createWallet() {
			if (!this.user.userId) {
				alert('用户信息异常，无法创建钱包');
				return;
			}

			this.$axios.post('VirtualWallet/UserId',this.$qs.stringify(
						{userId: this.user.userId}
					))
				.then(res => {
					alert('钱包创建成功');
					this.loadBalance(); // 创建钱包后加载余额
				}).catch(err => {
					console.error('创建钱包失败:', err.response || err);
					alert('创建钱包失败: ' + (err.response?.data?.message || err.message));
				});
		},

		// 加载余额
		loadBalance() {
			if (!this.user.walletId) {
				console.error('钱包ID缺失，无法获取余额');
				return;
			}

			this.$axios.get('VirtualWallet/UserId',{
					params: {
						userId: this.user.userId,
					}
				})
				.then(res => {
					this.balance = res.data.result.balance || 0;
					this.walletId=res.data.result.walletId;
				}).catch(err => {
					console.error('获取余额失败:', err.response || err);
					alert('获取余额失败: ' + (err.response?.data?.message || err.message));
				});
		},

		// 充值
		recharge() {
			if (this.rechargeAmount <= 0) {
				alert('请输入有效的充值金额');
				return;
			}
			if (!this.user.walletId) {
				alert('钱包ID异常，无法充值');
				return;
			}

			this.$axios.post('VirtualWallet/ToWalletId', 
					this.$qs.stringify({
						amount: this.rechargeAmount,
						walletId:this.walletId
					}
				
			)).then(() => {
				alert('充值成功');
				this.loadBalance();
			}).catch(err => {
				console.error('充值失败:', this.rechargeAmount);
				alert('充值失败: ' + (err.response?.data?.message || err.message));
			});
		},

		// 提现
		withdraw() {
			if (this.withdrawAmount <= 0) {
				alert('请输入有效的提现金额');
				return;
			}
			if (this.withdrawAmount > this.balance) {
				alert('余额不足');
				return;
			}
			if (!this.user.walletId) {
				alert('钱包ID异常，无法提现');
				return;
			}

			this.$axios.post(`VirtualWallet/FromWalletId`, 
				this.$qs.stringify({
							amount: this.withdrawAmount,
							walletId:this.walletId
						}
					
				)
			).then(() => {
				alert('提现成功');
				this.loadBalance();
			}).catch(err => {
				console.error('提现失败:', err.response || err);
				alert('提现失败: ' + (err.response?.data?.message || err.message));
			});
		}
	},
	components: {
		Footer
	}
};
</script>
<style scoped>
.wrapper header {
	width: 100%;
	height: 12vw;
	background-color: #0097FF;
	color: #fff;
	font-size: 4.8vw;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
	display: flex;
	justify-content: center;
	align-items: center;
}

.back-btn {
	position: absolute;
	left: 4vw;
	font-size: 6vw;
}

.content-box {
	margin-top: 12vw;
	padding-bottom: 14vw;
}

.wallet-summary {
	text-align: center;
	padding: 4vw;
	background: #fff;
	border-radius: 2vw;
	box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.summary-item span {
	font-size: 3.8vw;
	color: #666;
}

.summary-item strong {
	font-size: 6vw;
	color: #0097FF;
	margin-top: 2vw;
	display: block;
}

.wallet-actions {
	background: #fff;
	margin-top: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.action-item {
	margin-bottom: 4vw;
	display: flex;
	gap: 2vw;
}

.create-wallet-btn {
	margin-top: 4vw;
	text-align: center;
}

.create-wallet-btn button {
	padding: 2vw 4vw;
	background-color: #0097FF;
	color: white;
	border-radius: 1vw;
	font-size: 3.8vw;
	border: none;
	cursor: pointer;
}

.create-wallet-btn button:hover {
	background-color: #007ACC;
}
</style>
